package com.sendpo.zjx.sendpo.activity;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.google.gson.Gson;
import com.sendpo.zjx.sendpo.R;
import com.sendpo.zjx.sendpo.domain.UserPersonCenterDomain;
import com.sendpo.zjx.sendpo.domain.UserPersonCenterGuestDomain;
import com.sendpo.zjx.sendpo.net.HttpCode;
import com.sendpo.zjx.sendpo.net.HttpUrl;
import com.sendpo.zjx.sendpo.table.User;
import com.sendpo.zjx.sendpo.utils.KeyBoardUtils;
import com.sendpo.zjx.sendpo.utils.Tools;
import com.sendpo.zjx.sendpo.utils.Xutils;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.common.util.DensityUtil;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import ch.ielse.view.imagewatcher.ImageWatcher;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * Created by Administrator on 2017/10/20.
 */

public class UserPersonCenterGuestActivity extends AppCompatActivity implements ImageWatcher.OnPictureLongPressListener {
    public UserPersonCenterDomain.DataBean dataBean;
    @BindView(R.id.cir_icon)
    CircleImageView cirIcon;
    @BindView(R.id.uname)
    TextView uname;
    @BindView(R.id.datetime)
    TextView datetime;
    @BindView(R.id.content)
    TextView content;
    @BindView(R.id.all_ll)
    LinearLayout allLl;
    @BindView(R.id.v_image_watcher)
    public ImageWatcher vImageWatcher;
    @BindView(value = R.id.recyclerview)
    public RecyclerView recyclerview;
   public LinearLayoutManager lm;
    @BindView(value = R.id.content_edit)
    public EditText content_edit;
    public int currentlastitem = 0;
    public boolean lastloading = false;
    private int pagenow=1;
    private RecylcerAdaper adpter;
      @BindView(value = R.id.sex_rl)
      public RelativeLayout sex_rl;
    @BindView(value = R.id.sex_iv)
    public ImageView sex_iv;
     @BindView(value = R.id.sex_tv)
     public TextView sex_tv;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Tools.initStatus(this, R.color.black);
        setContentView(R.layout.activity_userpersoncenterguest);
        ButterKnife.bind(this);
        initComponent();
        pagenow=1;
        query(pagenow,dataBean.getDynamicId());
    }

    private void initComponent() {
        lm=new LinearLayoutManager(this, OrientationHelper.VERTICAL,false){
            @Override
            public boolean canScrollVertically() {

                return false;
            }
        };
        recyclerview.setLayoutManager(lm);
        vImageWatcher.setTranslucentStatus(0); // 如果是透明状态栏，你需要给ImageWatcher标记 一个偏移值，以修正点击ImageView查看的启动动画的Y轴起点的不正确
        vImageWatcher.setErrorImageRes(R.mipmap.error_picture); // 配置error图标 如果不介意使用lib自带的图标，并不一定要调用这个API
        vImageWatcher.setOnPictureLongPressListener(this); // 长按图片的回调，你可以显示一个框继续提供一些复制，发送等功能
        dataBean = (UserPersonCenterDomain.DataBean) getIntent().getSerializableExtra("data");
        if (dataBean != null) {
            addWatch(dataBean.getDynamicId()+"");
            Glide.with(this)
                    .load("" + dataBean.getUseravatar())
                    .asBitmap()
                    .animate(R.anim.fade_in)
                    .override(300, 300)
                    .centerCrop()
                    .into(new SimpleTarget<Bitmap>() {
                        @Override
                        public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                            cirIcon.setImageBitmap(resource);
                        }
                    });
            uname.setText("" + dataBean.getUsername());

            datetime.setText("" + new SimpleDateFormat("yyyy年MM月dd日").format(Tools.getStringtoDate(dataBean.getDynamicCreatetime(), "yyyy-MM-dd HH:mm:ss")));
            content.setText("" + dataBean.getDynamicComment());
            allLl .removeAllViews();
            List<String> imgs = dataBean.getImgs();
            if (imgs != null && imgs.size() != 0) {
                final List<String> ivs_s = new ArrayList<>();
                final List<ImageView> ivs = new ArrayList<>();
                for (String img : imgs) {
                    final ImageView iv = new ImageView(UserPersonCenterGuestActivity.this);
                    iv.setScaleType(ImageView.ScaleType.CENTER_CROP);
                    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(DensityUtil.dip2px(158), DensityUtil.dip2px(158));
                    lp.setMargins(DensityUtil.dip2px(10), 0, DensityUtil.dip2px(10), 0);
                    iv.setLayoutParams(lp);
                    iv.setBackgroundColor(getResources().getColor(R.color.default_lightgray));
                    Glide.with(UserPersonCenterGuestActivity.this)
                            .load(img)
                            .asBitmap()
                            .animate(R.anim.fade_in)
                            .placeholder(getResources().getColor(R.color.default_lightgray))
                            .override(500, 500)
                            .into(iv);
                    iv.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            vImageWatcher.show(iv, ivs, ivs_s);
                        }
                    });
                    ivs.add(iv);
                    ivs_s.add(img);
                    allLl.addView(iv);
                }
            }

            if(dataBean.getUsersex()==0){
               sex_rl.setBackgroundColor(getResources().getColor(R.color.default_blue));
            sex_iv.setImageResource(R.mipmap.sex_male_while);
            }else{
              sex_rl.setBackgroundColor(getResources().getColor(R.color.colorAccent));
               sex_iv.setImageResource(R.mipmap.sex_female_while);
            }
           sex_tv.setText(""+dataBean.getUserage());
        }
    }

    @OnClick(value = {R.id.backbt, R.id.send_bt})
    public void onMyClick(View view) {
        switch (view.getId()) {
            case R.id.backbt:
                finish();
                break;
            case R.id.send_bt:
                List<User> userList= Xutils.queryAll(getApplication(),User.class);
                      if(userList==null||userList.size()==0){
                        Tools.redirectActivity(UserPersonCenterGuestActivity.this,LoginActivity.class);
                          return;
                      }
                if(TextUtils.isEmpty(content_edit.getText().toString().trim())){
        Toast.makeText(getApplicationContext(),"评论不能空",Toast.LENGTH_SHORT).show();
                    return;
                }
                addGuest(dataBean.getDynamicId()+"",userList.get(0).getUserId()+"",content_edit.getText().toString().trim());
                content_edit.getText().clear();
                KeyBoardUtils.closeKeybord(content_edit,this);
                break;
        }
    }

    @Override
    public void onPictureLongPress(ImageView v, String url, int pos) {

    }

    public void addWatch(String dynamicId){
        Map<String,String> map=new HashMap<>();
              map.put("dynamicId",""+dynamicId);
        Xutils.POST(HttpUrl.dynamicwatchinfoadd, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    public  void addGuest(String dynamicId,String userId,String content){
          Map<String,String > map=new HashMap<>();
        map.put("userId",""+userId);
        map.put("dynamicId",""+dynamicId);
        map.put("Text",content);
        Xutils.POST(HttpUrl.userdynamiccommentsAdd, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                try {
                    JSONObject jsonObject=new JSONObject(result);
                    Toast.makeText(getApplicationContext(),jsonObject.getString("message"),Toast.LENGTH_SHORT).show();
                switch (jsonObject.getInt("state")){
                    case HttpCode.SUCCESS:
                        pagenow=1;
                        query(pagenow,dataBean.getDynamicId());
                        break;
                }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Toast.makeText(getApplicationContext(),"请稍后重试",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    public class RecylcerAdaper extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
        public List<UserPersonCenterGuestDomain.DataBean> dataBeen;
        public LayoutInflater inflater;

        public RecylcerAdaper(List<UserPersonCenterGuestDomain.DataBean> dataBeen, Context context) {
            inflater = LayoutInflater.from(context);
            this.dataBeen = dataBeen;
        }
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            RecyclerView.ViewHolder ih = null;
            ih = new IndexHoler(inflater.inflate(R.layout.layout_userguest_listitem, parent, false));
            return ih;
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
            final IndexHoler ih = (IndexHoler) holder;
            final UserPersonCenterGuestDomain.DataBean dataBean=dataBeen.get(position);
                                 System.out.println("****************"+dataBean.getUserAvatarpath());
            ih.cir_icon.setImageResource(R.drawable.nim_avatar_default);
            Glide.with(UserPersonCenterGuestActivity.this)
                           .load(dataBean.getUserAvatarpath()+"")
                   .          asBitmap().
                           placeholder(R.drawable.nim_avatar_default)
                   .animate(R.anim.fade_in)
                           .centerCrop()
                           .into(new SimpleTarget<Bitmap>() {
                               @Override
                               public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                        ih.cir_icon.setImageBitmap(resource);
                               }
                           });
            ih.cir_icon.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Map<String,Object> map=new HashMap<>();
                    map.put("id",dataBean.getUserId());
                    Tools.redirectActivity(UserPersonCenterGuestActivity.this, UserPersonCenterActivity.class,map);
                }
            });
            ih.name.setText(""+dataBean.getUserName());
             if(!TextUtils.isEmpty(dataBean.getCommentsCreatetime())){
                 ih.dateitme.setText(new SimpleDateFormat("yyyy年MM月dd日").format(Tools.getStringtoDate(dataBean.getCommentsCreatetime(),"yyyy-MM-dd HH:mm:ss"))+"");
            }
               ih.content.setText(""+dataBean.getCommentText());
        }

        @Override
        public int getItemCount() {
            return dataBeen.size();
        }

        public class IndexHoler extends RecyclerView.ViewHolder {
            public View rootView;
              public CircleImageView cir_icon;
            public TextView name;
            public TextView dateitme;
            public TextView content;
            public IndexHoler(View itemView) {
                super(itemView);
                rootView = itemView;
                cir_icon=itemView.findViewById(R.id.cir_icon);
                name=itemView.findViewById(R.id.name);
                dateitme=itemView.findViewById(R.id.dateitme);
                content=itemView.findViewById(R.id.content);
            }
        }

        public void initRefresh(List<UserPersonCenterGuestDomain.DataBean> domains) {
            this.dataBeen.removeAll(this.dataBeen);
            this.dataBeen.addAll(domains);
            notifyDataSetChanged();
        }

        public void initAppend(List<UserPersonCenterGuestDomain.DataBean> domains) {
            this.dataBeen.addAll(domains);
            notifyDataSetChanged();
        }

        public void delete(int position) {
            this.dataBeen.remove(position);
            notifyDataSetChanged();
        }

    }

    public void query(int pagenow, final int dynamicId) {
        Map<String, String> map = new HashMap<>();
        map.put("pagenow", pagenow + "");
        map.put("dynamicId", dynamicId + "");
        Xutils.POST(HttpUrl.userdynamiccommentsQuery, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Gson gson = new Gson();
                UserPersonCenterGuestDomain domain = gson.fromJson(result, UserPersonCenterGuestDomain.class);
                switch (domain.getState()) {
                    case HttpCode.SUCCESS:
                        if (domain.getData() != null && domain.getData().size() != 0) {
                            if (adpter == null) {
                                recyclerview.setAdapter(adpter = new RecylcerAdaper(domain.getData(), UserPersonCenterGuestActivity.this));
                                recyclerview.setOnScrollListener(new RecyclerView.OnScrollListener() {
                                    @Override
                                    public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                                        super.onScrollStateChanged(recyclerView, newState);
                                        if (currentlastitem == lm.getItemCount() - 1 && newState == RecyclerView.SCROLL_STATE_IDLE) {
                                            if (UserPersonCenterGuestActivity.this.pagenow == 1 && adpter.dataBeen.size() >= 10 && lastloading == false) {
                                                UserPersonCenterGuestActivity.this.pagenow++;
                                                append(UserPersonCenterGuestActivity.this.pagenow, dynamicId);
                                            }
                                        }
                                    }

                                    @Override
                                    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                                        super.onScrolled(recyclerView, dx, dy);
                                        currentlastitem = lm.findLastVisibleItemPosition();
                                    }
                                });
                            } else {
                                adpter.initRefresh(domain.getData());
                            }

                        }
                        break;
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    public void append(int pagenow, final int dynamicId) {
        lastloading = true;
        Map<String, String> map = new HashMap<>();
        map.put("pagenow", pagenow + "");
        map.put("dynamicId", dynamicId + "");
        Xutils.POST(HttpUrl.userdynamiccommentsQuery, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                lastloading = false;
                Gson gson = new Gson();
                UserPersonCenterGuestDomain domain = gson.fromJson(result, UserPersonCenterGuestDomain.class);
                switch (domain.getState()) {
                    case HttpCode.SUCCESS:
                        if (domain.getData() != null && domain.getData().size() != 0) {
                            if (adpter == null) {
                                recyclerview.setAdapter(adpter = new RecylcerAdaper(domain.getData(), UserPersonCenterGuestActivity.this));
                                recyclerview.setOnScrollListener(new RecyclerView.OnScrollListener() {
                                    @Override
                                    public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                                        super.onScrollStateChanged(recyclerView, newState);
                                        if (currentlastitem == lm.getItemCount() - 1 && newState == RecyclerView.SCROLL_STATE_IDLE) {
                                            if (UserPersonCenterGuestActivity.this.pagenow == 1 && adpter.dataBeen.size() >= 10 && lastloading == false) {
                                                UserPersonCenterGuestActivity.this.pagenow++;
                                                append(UserPersonCenterGuestActivity.this.pagenow, dynamicId);
                                            }
                                        }
                                    }

                                    @Override
                                    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                                        super.onScrolled(recyclerView, dx, dy);
                                        currentlastitem = lm.findLastVisibleItemPosition();
                                    }
                                });
                            } else {
                                adpter.initAppend(domain.getData());
                            }

                        }
                        break;
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                lastloading = false;
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

}
